package cn.itsource.iploading;

import cn.hutool.core.util.StrUtil;
import cn.itsource.mapper.blog.IpAddressMapper;
import cn.itsource.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@Service
public class BlogArticleService {
    @Autowired
    IpAddressMapper ipAddressMapper;



    public JsonResult updateStar(Integer id, HttpServletRequest request) throws Exception{
        //通过文章id查询ip地址
        List<String> address = ipAddressMapper.findByArticleId(id);
        //获取请求中的地址
        if (request == null) {
            throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
        }
        String ip = request.getHeader("x-forwarded-for");
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (address.contains(ip)){//数据库有ip地址 - 以前点赞了 - 再点就是取消点赞
            IpAddress ipAddress1 = new IpAddress();
            ipAddress1.setIp(ip);
            ipAddress1.setArticleId(id);
            ipAddressMapper.delByIpAndArticleId(ipAddress1);
            ipAddressMapper.decreStar(id);
            return JsonResult.success("cancel");
        }else {
            IpAddress ipAddress = new IpAddress();
            ipAddress.setIp(ip);
            ipAddress.setArticleId(id);
            ipAddressMapper.add(ipAddress);
            ipAddressMapper.increStar(id);
            return JsonResult.success("ok");
        }
    }


    public JsonResult initIconClass(Integer id, HttpServletRequest request) {
        List<String> ips = ipAddressMapper.findByArticleId(id);
        Integer i =ipAddressMapper.countStar(id);
        String ip = request.getRemoteAddr();
        HashMap<String, Object> data = new HashMap<>();
        data.put("starNum",i);
        if (ips.contains(ip)){//数据库有mac地址 - 以前点赞过 - 再点就是取消点赞
            data.put("like","ok");
            return JsonResult.success(data);
        }else {
            data.put("like","no");
            return JsonResult.success(data);
        }
    }
    
}
